package it.polimi.swKnights.SWIMv2.servlets.registration;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.CannotDeleteFounderAccountException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.registration.DeleteAccountRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;

import javax.persistence.EntityNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class DeleteAccountProceed
 */
public class DeleteAccountProceed extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("userName");

		String password = request.getParameter("password");
		String confirmPassword = request.getParameter("confirm_password");
		String email = request.getParameter("email");

		DeleteAccountRemote deleteAccoutRemote = this
				.lookUp(DeleteAccountRemote.class);
		try
		{
			this.checkPasssword(password, confirmPassword);
			deleteAccoutRemote.deleteAccountOfUser(username, password, email);

			session.setAttribute("userName", null);
			session.setAttribute("password", null);

			response.sendRedirect("./siteHome");

		}
		catch (EntityNotFoundException e)
		{
			// non dovrebbe mai succedere questo!
			response.sendRedirect("./deleteAccount?error=" + Errors.noexistuser);

		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./deleteAccount?error="
					+ Errors.wrongpass);

		}
		catch (CannotDeleteFounderAccountException e)
		{
			response.sendRedirect("./deleteAccount?error="
					+ Errors.founderDelete);

		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./deleteAccount?error=" + Errors.notuser);
		}

	}

	private void checkPasssword(String password, String confirmPassword)
			throws LoginFailException
	{
		if (password == null || confirmPassword == null)
		{
			throw new LoginFailException();
		}
		else if (!password.equals(confirmPassword))
		{
			throw new LoginFailException();
		}

	}
}
